package com.yidianyanglao.buyBack.controller;

import com.alibaba.druid.util.StringUtils;
import com.yidianyanglao.buyBack.bean.BankOtherBean;
import com.yidianyanglao.buyBack.bean.BankcardBean;
import com.yidianyanglao.buyBack.bean.RepurchaseRecordBean;
import com.yidianyanglao.buyBack.mapper.BuyBackMapper;
import com.yidianyanglao.buyBack.service.BuyBackService;
import com.yidianyanglao.common.mapper.CommonMapper;
import com.yidianyanglao.core.bean.ErrorReocrd;
import com.yidianyanglao.core.bean.MobileCode;
import com.yidianyanglao.core.bean.RetBean;
import com.yidianyanglao.core.enums.Code;
import com.yidianyanglao.core.exception.CustomException;
import com.yidianyanglao.core.util.DateUtils;
import com.yidianyanglao.core.util.DigestUitl;
import com.yidianyanglao.core.util.GetIp;
import com.yidianyanglao.user.bean.UserBean;
import com.yidianyanglao.user.mapper.UserMapper;
import com.yidianyanglao.user.service.UserService;
import com.yidianyanglao.userData.mapper.UserDataMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * describe :   ------      ------
 * author  :        lf
 * time on  :   ${DAte}  16:22.
 * ----------------------------------------------------
 */
@Controller
public class BuyBackController {

    @Resource
    private BuyBackMapper bbm;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserDataMapper udm;

    @Resource
    private BuyBackService buyBackService;

    @Resource
    private CommonMapper commonMapper;

    @Resource
    private UserService userService;

    /**
     * 绑定银行卡
     * @param request
     * @param bb
     * @return
     */
    @RequestMapping("/expressive/addBank.json")
    @ResponseBody
    public RetBean addBank(HttpServletRequest request,BankcardBean bb,String code){

        UserBean userBean = (UserBean) request.getAttribute("request_user");

        if(code==null||code.equals("")||code.equals("null") || bb.getUserName()==null||bb.getUserName().equals("")||bb.getUserName().equals("null") || bb.getMobile()==null||bb.getMobile().equals("")||bb.getMobile().equals("null") || bb.getCardusername()==null||bb.getCardusername().equals("")||bb.getCardusername().equals("null") || bb.getCardnumber()==null||bb.getCardnumber().equals("")||bb.getCardnumber().equals("null") || bb.getIdnumber()==null||bb.getIdnumber().equals("")||bb.getIdnumber().equals("null") || bb.getBankName()==null||bb.getBankName().equals("")||bb.getBankName().equals("null")){
            throw new CustomException(Code.ERROR, "参数均不能为空");
        }

        if(!checkMobile(bb.getMobile(),code)){
            throw new CustomException(Code.ERROR,"验证码验证失败！");
        }

        if(bbm.getBankCardByCardnumber(bb.getCardnumber(),userBean.getId()).size()>0){
            throw new CustomException(Code.ERROR, "该银行卡已添加");
        }

        if(StringUtils.isEmpty(bb.getBranchName())){
            throw new CustomException(Code.ERROR, "支行信息不能为空");
        }

        bb.setUserId(userBean.getId());
        bb.setUserName(bb.getUserName());
        bb.setMobile(bb.getMobile());
        bb.setCardusername(bb.getCardusername());
        bb.setCardnumber(bb.getCardnumber());
        bb.setIdnumber(bb.getIdnumber());
        bb.setBankName(bb.getBankName());
        bb.setBranchName(bb.getBranchName());

        int isOK = bbm.addBankcard(bb);

        if( isOK == 1){
            BankcardBean newBank = bbm.getBankCardByCardnumber(bb.getCardnumber(),userBean.getId()).get(0);
            BankOtherBean bo = bbm.getBankOtherByName(bb.getBankName());
            if(bo!=null){
                newBank.setImgurl(bo.getImgUrl());
                newBank.setLogourl(bo.getLogourl());
            }
            return new RetBean(Code.SUCCESS,"请求成功",newBank);
        }else{
            throw new CustomException(Code.ERROR, "添加银行卡失败");
        }
    }

    /**
     * 解绑银行卡
     * @param request
     * @param bankid
     * @return
     */
    @RequestMapping("/expressive/delBank.json")
    @ResponseBody
    public RetBean delBank(HttpServletRequest request,String bankid,String paypwd){
        UserBean userBean = (UserBean) request.getAttribute("request_user");
        //五次支付错误拦截
        if(commonMapper.getErrorRecordCount(1,userBean.getId(),DateUtils.getToday())>=5){
            throw new CustomException(Code.PAYWARNING, "您今天已累计5次输入错误的支付密码，账户已被锁定，请于24小时后再操作。如需紧急解锁，请联系客服，客服电话。");
        }
        if(!userBean.getPaypwd().equals(DigestUitl.MD5LowerCase(paypwd))){
            ErrorReocrd errorReocrd = new ErrorReocrd(1,userBean.getId(), GetIp.getIp(request),"支付密码错误："+paypwd);
            commonMapper.addErrorRecord(errorReocrd);
            if(commonMapper.getErrorRecordCount(1,userBean.getId(),DateUtils.getToday())==3){
                //三次提示
                throw new CustomException(Code.ERROR, "您今天已累计3次输入错误的支付密码，再输错2次您的账户将被锁定24小时，请谨慎操作。");
            }else if(commonMapper.getErrorRecordCount(1,userBean.getId(),DateUtils.getToday())>=5){
                //五次锁定，更新用户
                userService.updateToken(userBean.getId());
                throw new CustomException(Code.PAYWARNING, "您今天已累计5次输入错误的支付密码，账户已被锁定，请于24小时后再操作。如需紧急解锁，请联系客服，客服电话。");
            }else{
                throw new CustomException(Code.ERROR,"支付密码错误");
            }
        }

        int isOK = bbm.deleteBankcard(String.valueOf(userBean.getId()),bankid);
        if( isOK == 1){
            return new RetBean(Code.SUCCESS,"银行卡删除成功",null);
        }else{
            throw new CustomException(Code.ERROR, "银行卡删除失败");
        }
    }

    /**
     * 获取支持的银行卡列表
     * @param request
     * @return
     */
    @RequestMapping("/expressive/bankList.json")
    @ResponseBody
    public RetBean bankList(HttpServletRequest request){
        List<BankOtherBean> list = bbm.getBankOtherList();
        return new RetBean(Code.SUCCESS,"请求成功",list);
    }

    /**
     * 获取我的银行卡列表
     * @param request
     * @return
     */
    @RequestMapping("/expressive/myBank.json")
    @ResponseBody
    public RetBean getBankcardList(HttpServletRequest request){
        UserBean userBean = (UserBean) request.getAttribute("request_user");

        List<BankcardBean> list = bbm.getBankcardList(String.valueOf(userBean.getId()));
        if(list.size()>0){
            for(BankcardBean b:list){
                BankOtherBean bb = new BankOtherBean();
                if(bb!=null){
                    b.setImgurl(bbm.getBankOtherByName(b.getBankName()).getImgUrl());
                    b.setLogourl(bbm.getBankOtherByName(b.getBankName()).getLogourl());
                }
            }
        }

        return new RetBean(Code.SUCCESS,"请求成功",list);
    }

    /**
     * 获取回购记录
     * @param request
     * @param pageNum
     * @param repurchaseState 状态  0：审核中 1：审核通过 2：审核不通过
     * @return
     */
    @RequestMapping("/expressive/myExpressive.json")
    @ResponseBody
    public RetBean myExpressive(HttpServletRequest request,String pageNum,String repurchaseState){
        UserBean userBean = (UserBean) request.getAttribute("request_user");

        if(repurchaseState==null || repurchaseState.equals("") || repurchaseState.equals("null") || pageNum==null || pageNum.equals("")|| pageNum.equals("null")){
            throw new CustomException(Code.ERROR, "参数均不能为空");
        }
        if(!isPositiveInteger(pageNum)){
            throw new CustomException(Code.ERROR, "pageNum只能是正整数");
        }
        List<RepurchaseRecordBean> list = new ArrayList<>();


        int begin = 0;
        if(Integer.valueOf(pageNum)>1){
            begin = (Integer.valueOf(pageNum) - 1)* 5;
        }
        //repurchaseState.equals("1,2")||repurchaseState.equals("0,1")||repurchaseState.equals("0,2")
        //IOS传递过来如果是1,2标识，查询已经成功的数据，此时，默认更改参数值查询成功或者失败的状态 1
        if(repurchaseState.equals("1,2")){
            repurchaseState = "1";
        }

        if(repurchaseState.equals("1")){
            //获取申请成功或者失败的
            list = bbm.myExpressive(begin,userBean.getId());
        }else{
            //获取所有申请中的
            list = bbm.myExpressives(begin,userBean.getId());
        }

        return new RetBean(Code.SUCCESS,"请求成功",list);
    }

    /**
     * 申请回购
     * @param request
     * @param bankId
     * @param paypwd
     * @param applySeednum 最低申请数：普通种子6个，奖励种子10个。
     * @param seedType 1：普通种子 2：奖励种子
     * @return
     */
    @RequestMapping("/expressive/addRepurchase.json")
    @ResponseBody
    public RetBean addRepurchase(HttpServletRequest request,String bankId,String paypwd,String applySeednum,String seedType){
        UserBean userBean = (UserBean) request.getAttribute("request_user");

        //五次支付错误拦截
        if(commonMapper.getErrorRecordCount(1,userBean.getId(),DateUtils.getToday())>=5){
            throw new CustomException(Code.PAYWARNING, "您今天已累计5次输入错误的支付密码，账户已被锁定，请于24小时后再操作。如需紧急解锁，请联系客服，客服电话。");
        }

        if(bankId==null||bankId.equals("")||bankId.equals("null") || paypwd==null||paypwd.equals("")||paypwd.equals("null") || applySeednum==null||applySeednum.equals("")||applySeednum.equals("null") || seedType==null||seedType.equals("")||seedType.equals("null")){
            throw new CustomException(Code.ERROR, "参数均不能为空");
        }
        if(!(seedType.equals("1") || seedType.equals("2"))){
            throw new CustomException(Code.ERROR, "回购类型只能是1：普通种子 2：奖励种子");
        }
        if(!isPositiveInteger(applySeednum)){
            throw new CustomException(Code.ERROR, "回购数量只能是正整数");
        }

        //普通种子总数 - 冻结种子数，如果小于当前转赠种子数，提示 ，当前有多少种子在冻结中
        //对普通种子进行冻结判断
        if(seedType.equals("1")){
            if(userBean.getFrozenSeed()>0){
                if(userBean.getOrdinarySeed()-userBean.getFrozenSeed()<Integer.parseInt(applySeednum)){
                    throw new CustomException(Code.ERROR,"当前有"+userBean.getFrozenSeed()+"在冻结中，无法回购");
                }
            }
        }
        BankcardBean bank = bbm.getBankCardById(bankId,userBean.getId());
        if(bank == null){
            throw new CustomException(Code.ERROR, "用户不存在该银行卡");
        }

        if(StringUtils.isEmpty(bank.getBranchName())){
            throw new CustomException(Code.ERROR, "银行卡信息不完善，请重新绑卡并完善支行信息！");
        }

        if(StringUtils.isEmpty(bank.getMobile())){
            throw new CustomException(Code.ERROR, "银行卡信息不完善，请重新绑卡并完善预留手机信息！");
        }

        if(!userBean.getPaypwd().equals(DigestUitl.MD5LowerCase(paypwd))){
            //密码错误记录
            ErrorReocrd errorReocrd = new ErrorReocrd(1,userBean.getId(), GetIp.getIp(request),"支付密码错误："+paypwd);
            commonMapper.addErrorRecord(errorReocrd);
            if(commonMapper.getErrorRecordCount(1,userBean.getId(),DateUtils.getToday())==3){
                //三次提示
                throw new CustomException(Code.ERROR, "您今天已累计3次输入错误的支付密码，再输错2次您的账户将被锁定24小时，请谨慎操作。");
            }else if(commonMapper.getErrorRecordCount(1,userBean.getId(),DateUtils.getToday())>=5){
                //五次锁定，更新用户
                userService.updateToken(userBean.getId());
                throw new CustomException(Code.PAYWARNING, "您今天已累计5次输入错误的支付密码，账户已被锁定，请于24小时后再操作。如需紧急解锁，请联系客服，客服电话。");
            }else{
                throw new CustomException(Code.ERROR,"支付密码错误");
            }
        }
        double num = 0.00;
        BigDecimal seedNum = new BigDecimal(applySeednum);

        //开始回购,进入事务
        buyBackService.buyBackApply(userBean.getToken(),applySeednum,bank,seedType,seedNum,num);

        //获取种子各种数据，同根据token获取数据保持一致
        userBean = udm.getUserById(userBean.getId());
        Map<String,Object> map = userMapper.getUserYesterdayExcitation(userBean.getId(),1, DateUtils.getToday());
        if(map != null){
            userBean.setYesterdayExcitationA(map.get("change_seed").toString());
            userBean.setYesterdayTreeNumA(map.get("luckytreenum").toString());
        }

        map = userMapper.getUserYesterdayExcitation(userBean.getId(),2,DateUtils.getToday());
        if(map != null){
            userBean.setYesterdayExcitationB(map.get("change_seed").toString());
            userBean.setYesterdayTreeNumB(map.get("luckytreenum").toString());
        }

        return new RetBean(Code.SUCCESS,"申请回购成功",userBean);

    }

    public boolean isPositiveInteger(String pageNum) {
        return isMatch("^\\+{0,1}[1-9]\\d*", pageNum);
    }

    private boolean isMatch(String regex, String pageNum){
        if (pageNum == null || pageNum.trim().equals("")) {
            return false;
        }
        Pattern pattern = Pattern.compile(regex);
        Matcher isNum = pattern.matcher(pageNum);
        return isNum.matches();
    }

    /**
     * 验证验证码
     * @param mobile
     * @param code
     * @return
     */
    public boolean checkMobile(String mobile ,String code){
        boolean bool = true;
        MobileCode mobileCode = userMapper.getMobileCode(mobile,code);
        if(mobileCode == null){
            bool = false;
        }else{
            userMapper.updateMobileCode(mobileCode.getId());
        }
        //更新使用状态
        return bool;
    }

}
